from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from utils.authentication import Authen
from cart import models, sercart
# Create your views here.


class Add(APIView):
    authentication_classes = [Authen]

    def post(self, request):
        user = request.data.get('user')
        course = request.data.get('course')
        info = models.Cart.objects.filter(user=user, course=course)
        if info:
            return Response({'code': 200, 'msg': '该课程已存在'})
        else:
            ser = sercart.SerCart(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 200, 'msg': '添加成功'})
            else:
                return Response({'code': 204, 'msg': ser.errors})


class CartList(APIView):
    authentication_classes = [Authen]

    def get(self, request):
        # 获取用户id
        user = request.query_params.get('user')
        datalist = models.Cart.objects.filter(user=user)
        cartlist = []
        total = 0  # 总价
        count = 0  # 课程总数量
        for i in datalist:
            course = {}
            course['id'] = i.id
            course['courseid'] = i.course.id
            course['name'] = i.course.name
            course['price'] = i.course.price
            course['img'] = str(i.course.image)
            course['createtime'] = i.course.createtime
            course['select'] = i.select
            cartlist.append(course)
            if i.select:
                count += 1
                total += i.course.price
        return Response({'msg': 'ok', 'cartlist': cartlist, 'total': total, 'count': count})


# 修改状态
class CartUpdata(APIView):
    authentication_classes = [Authen]

    def put(self, request):
        id = request.data.get('id')
        cartlist = models.Cart.objects.filter(id=id).first()
        # print(cartlist)
        # print(cartlist.select)
        cartlist.select = not cartlist.select
        cartlist.save()
        return Response({'mag': '修改成功'})


# 删除单个
class CartDel(APIView):
    authentication_classes = [Authen]

    def delete(self, request):
        id = request.query_params.get('id')
        models.Cart.objects.filter(id=id).delete()
        return Response({'msg': '删除成功'})


# 批量删除
class CartMany(APIView):
    authentication_classes = [Authen]

    def delete(self, request):
        id = request.query_params.get('user')
        models.Cart.objects.filter(user=id, select=True).delete()
        return Response({'msg': '批量删除成功'})


# 全选
class CartAll(APIView):
    authentication_classes = [Authen]

    def put(self, request):
        id = request.data.get('user')
        status = request.data.get('status')
        models.Cart.objects.filter(user=id).update(select=status)
        if status:
            return Response({'msg': '全选成功'})
        else:
            return Response({'msg': '取消取消全选成功'})
